package ca.llsutherland.nfl.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.nfl.domain.Role;
import ca.llsutherland.nfl.exception.ValidationException;
import ca.llsutherland.nfl.helper.RoleHelper;
import ca.llsutherland.nfl.util.StringUtil;

public class RoleDao extends BaseDao {

	   private static RoleDao instance = new RoleDao();

	    @Override
	    public String getUnderlyingTableName() {
	        return "ROLE";
	    }

	    public static RoleDao getInstance() {
	        return instance ;
	    }

	    public Role findByName(String name) {
	        String findByNameQuery = getFindByNameQuery(name);
	        return buildRole(findByNameQuery);
	    }

	    private Role buildRole(String sql) {
	        Role role = null;
	        ResultSet rs = super.findByQuery(sql);
	        
	        try {
	            if(rs.next()){
	            	role = RoleHelper.createNewRole(Long.valueOf(rs.getLong("ID")), rs.getString("NAME"));
	            }
	            rs.close();
	        } catch (SQLException e) {
	            throw new ValidationException(e.getMessage() + " in buildRole()");
	        } finally {
	            rs = null;            
	        }
	        return role;
	    }

	    public Role create(Role role) {
	        String sql = "INSERT INTO " + getUnderlyingTableName() + " (NAME) VALUES (" + StringUtil.addSingleQuotes(role.getName()) + ");";
	        return findById(super.create(sql));
	    }

	    public Role findById(Long id) {
	        String findByIdQuery = getFindByIdQuery(id);
	        return buildRole(findByIdQuery);
	    }

}
